<template>
  <div class="form-part-return">
    <div class="">
      <span class="link" @click="returnToLibrary('personal')">{{ $t('task.detail.returnToPersonal') }}</span>
      <span class="link" @click="returnToLibrary('storehouse')">{{ $t('task.detail.returnToStorehouse') }}</span>
    </div>

    <el-table v-table-style v-loading="listLoading" :style="tableBorderBottomStyle" header-row-class-name="base-table-header-v3" row-class-name="base-table-row-v3" :data="value"
      max-height="500">
      <template slot="empty">
        <BaseListForNoData
          v-show="!listLoading"
          table-type="smallTable"
          :notice-msg="$t('common.base.tip.noData')"
        ></BaseListForNoData>
      </template>
      <el-table-column v-for="(column, index) in tableColumns" :key="`${column.fieldName}_${index}`"
        :label="column.displayName" :prop="column.fieldName" :width="column.width"
        :fixed='column.isFixed'>
        <template slot-scope="scope">
          <!-- start 返还仓库 -->
          <template v-if="column.fieldName === 'repertoryId'">
            <!-- 返还个人 -->
            <div v-if="scope.row.isPerson">
                <template v-if="isOpenData">
                    <open-data ref="openDataRef" type="userName" :openid="loginUserInfo.staffId"></open-data>
                </template>
                <template v-else>{{ loginUserInfo.displayName }}</template>
            </div>
            <!-- 返还仓库 -->
            <template v-else>
              <el-select 
                v-if="scope.row.repertoryId" 
                class='sale-price-select' 
                :value="`${scope.row.repertoryId}/${scope.row.repertoryName}`"
                @change="changeWarehouse($event, scope.$index)"
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  >
                </el-option>
              </el-select>
            </template>
        </template>
        <!-- end 返还仓库 -->

        <!-- start 操作 -->
        <template v-else-if="column.fieldName === 'action'">
          <el-button class="text-danger" type="text" size="mini" @click="deleteItem(scope)">{{$t('common.base.delete')}}</el-button>
        </template>
        <!-- end 操作 -->
          <template v-else>{{ $formatFormField(column, scope.row) }}</template>
        </template>
      </el-table-column>
    </el-table>

    <parts-return-dialog
      ref="PartsReturnDialog"
      :field="field"
      :cardSparepartList="cardSparepartList"
      :warehouse-list="warehouseList"
      :columns="tableColumns"
      @submit="addPart"
    />
</div>
</template>

<script>
import FormMixin from '@src/component/form/mixin/form';
import { t } from '@src/locales';
import _ from 'lodash';
import * as SettingApi from '@src/api/SettingApi.ts';
import { isOpenData } from '@src/util/platform';
import { getRootWindow } from '@src/util/dom';
// components
import PartsReturnDialog from './components/PartsReturnDialog.vue';

export default {
  name: 'form-spare-parts-return',
  mixins: [FormMixin],
  props: {
    value: {
      type: Array,
      default: () => ([])
    },
  },
  components: {
    [PartsReturnDialog.name]: PartsReturnDialog
  },
  data() {
    return {
      listLoading: false,
      tableAllData: [],
      cardSparepartList: [],
      warehouseList: [],
      isOpenData,
    }
  },
  computed: {
    // 表格样式
    tableBorderBottomStyle() {
      return {
        'border-bottom': this.tableAllData?.length ? 'none' : '1px solid #e8e8e8'
      }
    },
    // 表格列
    tableColumns() {
        const field = (this.field?.setting?.sparePartFieldList || []).map(x => {
          if(x.fieldName === 'serialNumber') {
            x.width = '220px';
          }
          return x;
        });

        return [
            ...field,
            {
                displayName: this.$t('common.base.operation'),
                fieldName: 'action',
                fixed: 'right',
                width: '70px'
            }
        ]
    },
    // 当前用户数据
    loginUserInfo() {
        const RootWindow = getRootWindow(window);
        const { userId, displayName, staffId } = RootWindow?.loginUser || {};
        return {
            userId,
            displayName,
            staffId
        }
    },
    tableData() {
      return this.value || [];
    }
  },
  mounted() {
    this.tableAllData = this.value || [];
    this.getWarehouseTableData();
    this.$eventBus.$on('task_receipt_update_config', this.setEditConfig);
  },
  beforeDestroy() {
    this.$eventBus.$off('task_receipt_update_config', this.setEditConfig);
  },
  methods: {
    setEditConfig(config) {
      this.cardSparepartList = config?.sparePartCardList || [];
    },
    // 返还至 个人/仓库
    returnToLibrary(type) {
      this.$refs.PartsReturnDialog.open(type);
    },
    // 删除行
    async deleteItem({row, $index}) {
      if (!await Platform.confirm(this.$t('part.detail.text7'))) return;

      this.tableAllData.splice($index, 1);
      this.update();
    },
    addPart(data) {
      // 创建一个新的映射（Map），以便快速查找和更新 this.tableAllData 中的项
      const tableAllDataMap = new Map(this.tableAllData.map(item => [item.id + item.repertoryId, item]));

      data.forEach(newItem => {
        const id = newItem.id + newItem.repertoryId;
        // 检查当前项是否在 tableAllDataMap 中
        if (tableAllDataMap.has(id)) {
          tableAllDataMap.get(id).number += newItem.number;
        } else {
          tableAllDataMap.set(id, newItem);
        }
      });

      // 将映射转换回数组，并更新 this.tableAllData
      this.tableAllData = Array.from(tableAllDataMap.values());
      this.update();
    },
    changeWarehouse($event, $index) {
      const primaryId = this.tableAllData[$index]?.primaryId ?? this.tableAllData[$index]?.id
      const [id, name] = $event.split('/');
      this.$set(this.tableAllData, $index, {
        ...this.tableAllData[$index],
        repertoryId: id,
        repertoryName: name,
        primaryId,
      })

      // 修复bug#38622 此时tableAllData的其他备件的repertoryId是eg'1ebd65df-d5a9-11ec-9d05-00163e304a25/商城库'，需要改下
      const data = this.tableAllData.map(x => {
        const item = _.cloneDeep(x);
        if(!x.isPerson) {
          const repertoryInfo = item.repertoryId?.split('/') || [];
          repertoryInfo?.length > 1 && (item.repertoryId = repertoryInfo[0]);
        }
        return item;
      })

      this.$emit('update', { field: this.field, newValue: data });
    },
    update() {
      const data = this.tableAllData.map(x => {
        const item = _.cloneDeep(x);
        item.primaryId = item.primaryId ?? item.id;
        delete item.id;

        if(!x.isPerson) {
          const repertoryInfo = item.repertoryId?.split('/') || [];
          if(repertoryInfo?.length > 1) {
            item.repertoryId = repertoryInfo[0];
            item.repertoryName = repertoryInfo[1];
          }
        }

        return item;
      })
      this.$emit('update', { field: this.field, newValue: data });
    },
    // 获取可选返还仓库
    getWarehouseTableData(){
      SettingApi.getRepertoryAllRepertory({keyword:this.keyword}).then((res) =>{
        if(res&&res.result){
          this.warehouseList = (res.result || []).map(x => {
            return {
              ...x,
              id: `${x.id}/${x.name}`
            }
          });
        }else{
          this.warehouseList = [];
        }
      }).catch((err)=>{
        this.warehouseList=[];
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.form-part-return {
  width: 100%;
  display: flex;
  flex-direction: column;

  .link {
    cursor: pointer;
    color: $color-primary-light-6;
    margin-right: 10px;
  }
}

.el-table {
  border: 1px solid #e8e8e8;

  .resolve-view {
    color: $color-primary;
    cursor: pointer;
  }
  .table-add-text {
    color: #BFBFBF;
    font-size: 14px;
    cursor: pointer;
  }

  .table-faultDesc-text {
    width: 80%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  
  .el-button {
    margin-bottom: 0;
  }
}
</style>
